package br.com.tooist.pong2;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Pong2GlBoard {
	// Our vertices.
	// 0--11   8--7
	// |  |    |  |
	// |  10---9  | middle line to be twice as tick as vertical ones
	// |  3----4  |
	// |  |    |  |
	// 1--2    5--6
	private float vertices[] = {
		-1.0f,  1.0f, 0.0f,  // 0, Top Left
		-1.0f, -1.0f, 0.0f,  // 1, Bottom Left
		-0.99f, -1.0f, 0.0f,  // 2
		-0.99f, -0.01f, 0.0f,  // 3
		 0.99f, -0.01f, 0.0f,  // 4
		 0.99f, -1.0f, 0.0f,  // 5
		 1.0f, -1.0f, 0.0f,  // 6, Bottom Right
		 1.0f,  1.0f, 0.0f,  // 7, Top Right
		 0.99f, 1.0f, 0.0f,  // 8
		 0.99f, 0.01f, 0.0f,  // 9
		-0.99f, 0.01f, 0.0f,  // 10
		-0.99f, 1.0f, 0.0f,  // 11
	};

	// The order we like to connect them.
	private short[] indices = { 0, 1, 2, 0, 2, 11, 10, 3, 9, 9, 3, 4, 8, 5, 6, 8, 6, 7 };

	// Our vertex buffer.
	private FloatBuffer vertexBuffer;

	// Our index buffer.
	private ShortBuffer indexBuffer;

	// __construct
	public Pong2GlBoard () {
		// a float is 4 bytes, therefore we multiply the number if
		// vertices with 4.
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);

		// short is 2 bytes, therefore we multiply the number if
		// vertices with 2.
		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
	}

	/**
	 * This function draws our square on screen.
	 * @param gl
	 */
	public void draw(GL10 gl) {
		gl.glColor4f(0.3f, 0.3f, 0.3f, 1.0f); // light gray
		// Enabled the vertices buffer for writing and to be used during rendering.
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		// Specifies the location and data format of an array of vertex coordinates to use when rendering.
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);
		// Disable the vertices buffer.
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	}

}
